package cn.ee.dfs.esb.controller;

import cn.ee.dfs.common.annotation.Log;
import cn.ee.dfs.common.controller.BaseController;
import cn.ee.dfs.common.entity.DfsResponse;
import cn.ee.dfs.common.entity.QueryRequest;
import cn.ee.dfs.common.entity.WebServiceMethodVo;
import cn.ee.dfs.common.entity.WsdlEntity;
import cn.ee.dfs.common.exception.DfsException;
import cn.ee.dfs.common.utils.WsdlUtils;
import cn.ee.dfs.esb.entity.ServiceInfo;
import cn.ee.dfs.esb.service.IServiceInfoService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author TWJ
 * @date 2019-07-31 17:02:37
 */
@Slf4j
@Validated
@RestController
@RequestMapping("serviceInfo")
public class ServiceInfoController extends BaseController {

    @Autowired
    private IServiceInfoService serviceInfoService;


//    @GetMapping("serviceInfo")
//    @RequiresPermissions("serviceInfo:list")
//    public DfsResponse getAllServiceInfos(ServiceInfo serviceInfo) {
//        return new DfsResponse().success().data(serviceInfoService.findServiceInfos(serviceInfo));
//    }

    @GetMapping("list")
    @RequiresPermissions("serviceInfo:view")
    public DfsResponse serviceInfoList(QueryRequest request, ServiceInfo serviceInfo) {
        Map<String, Object> dataTable = getDataTable(this.serviceInfoService.findServiceInfos(request, serviceInfo));
        log.info("-- serviceInfoList  --" + dataTable);
        return new DfsResponse().success().data(dataTable);
    }

    @Log("新增ServiceInfo")
    @PostMapping("add")
    @RequiresPermissions("serviceInfo:add")
    public DfsResponse addServiceInfo(@Valid ServiceInfo serviceInfo) throws DfsException {
        try {
            this.serviceInfoService.createServiceInfo(serviceInfo);
            return new DfsResponse().success();
        } catch (Exception e) {
            String message = "新增ServiceInfo失败";
            log.error(message, e);
            throw new DfsException(message);
        }
    }

    @Log("删除服务")
    @GetMapping("delete/{serviceIds}")
    @RequiresPermissions("serviceInfo:delete")
    public DfsResponse deleteServiceInfo(@NotBlank(message = "{required}") @PathVariable String serviceIds) throws DfsException {
        try {
            String[] ids = serviceIds.split(StringPool.COMMA);
            this.serviceInfoService.deleteServiceInfo(ids);
//            this.serviceInfoService.deleteUsers(ids);
            return new DfsResponse().success();
        } catch (Exception e) {
            String message = "删除ServiceInfo失败";
            log.error(message, e);
            throw new DfsException(message);
        }
    }

    @Log("修改服务")
    @PostMapping("update")
    @RequiresPermissions("serviceInfo:update")
    public DfsResponse updateServiceInfo(ServiceInfo serviceInfo) throws DfsException {
        try {
            if (serviceInfo.getServiceId() == null) {
                throw new DfsException("服务ID为空");
            }
            this.serviceInfoService.updateServiceInfo(serviceInfo);
            return new DfsResponse().success();
        } catch (Exception e) {
            String message = "修改ServiceInfo失败";
            log.error(message, e);
            throw new DfsException(message);
        }
    }


    @GetMapping("excel")
    @RequiresPermissions("serviceInfo:export")
    public void export(QueryRequest queryRequest, ServiceInfo serviceInfo, HttpServletResponse response) throws DfsException {
        try {
            List<ServiceInfo> serviceInfos = this.serviceInfoService.findServiceInfos(queryRequest, serviceInfo).getRecords();
            ExcelKit.$Export(ServiceInfo.class, response).downXlsx(serviceInfos, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new DfsException(message);
        }
    }

    @GetMapping("pv/{serviceId}/{range}")
    public DfsResponse pv(@PathVariable("serviceId") String serviceId, @PathVariable("range") String range) throws DfsException {
        try {
            switch (range) {
                case "y"://年
                    break;
                case "M"://月
                    break;
                case "d"://日
                    break;
            }
            Integer callCount = serviceInfoService.getCallCount(Integer.parseInt(serviceId), range);
            return new DfsResponse().success().data(callCount);
        } catch (Exception e) {
            String message = "访问量查询失败";
            throw new DfsException(message);
        }
    }

    @RequestMapping("wsMethods")
    @ResponseBody
    public DfsResponse test(@RequestParam String wsdlUri) {
        log.info("-- /wsMethods --");
        List<WsdlEntity> wsdlEntities = WsdlUtils.getMethods(wsdlUri);
        List<WebServiceMethodVo> webserviceMethodInfos = new ArrayList<>();
        for (WsdlEntity w : wsdlEntities) {
//            String json = new Gson().toJson(w.getMethodParams());
            String json = JSONObject.toJSONString(w.getMethodParams());
            try {
                String paramNames = Base64.encodeBase64String(json.getBytes("utf-8"));
                webserviceMethodInfos.add(new WebServiceMethodVo(w.getTargetNamespace(), w.getMethodName(), paramNames));
//                webserviceMethodInfos.add(new WebServiceMethodVo(w.getTargetNamespace(), w.getMethodName(), json));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        log.info("webserviceMethodInfos ->" + webserviceMethodInfos);
        return new DfsResponse().success().data(webserviceMethodInfos);
    }

}
